package com.bluesky.jwf.component.validator;

import java.util.ArrayList;
import java.util.List;

import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.javawebbrowser.domain.html.tags.TagNotFoundException;
import com.bluesky.jwf.ComponentFactory;
import com.bluesky.jwf.component.Component;
import com.bluesky.jwf.component.list.ListView;

public class GroupValidator extends Validator {
	protected List<Validator> validators = new ArrayList<Validator>();

	protected ListView messageListView;
	protected Tag messageListTag;

	public GroupValidator() {

	}

	@Override
	public void init(String html) {
		
		try {
			super.init(html);
		} catch (TagNotFoundException e) {
			//this is a trick. catch the exception raise by 'messageTag = loadByJwfClass("message");'
			//and it is harmless.
		}
		
		
		messageListTag = loadByJwfClass("list");

		messageListView = (ListView) ComponentFactory.getInstance()
				.createComponent("ListView", messageListTag.toHtml());
		messageListView.setItemClass(MessageListItem.class);

		messageListTag.replace(messageListView);

	}

	public void addValidator(Validator validator) {

		validators.add(validator);

		messageListView.setModel(validators);
		messageListView.dataBind();
	}

	@Override
	public void validate() {
		setResult(true);
		for (Validator v : validators) {
			v.validate();
			if (!v.getResult())
				setResult(false);
		}
		messageListView.dataBind();
	}

	@Override
	public void setResult(boolean result) {
		this.result = result;

		if (!result)
			messageListTag.setStyleAttribute("color", "red");
		else
			messageListTag.removeStyleAttribute("color");
	}
}
